package com.example.testproj.lrucache;

import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.support.v4.util.LruCache;
import android.util.Log;
import android.widget.ImageView;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @des:
 * @author: 芮勤
 * @date: 2019/8/8 10:02
 * @see {@link }
 */
public class ImageGetUtils {
    private static final String TAG = "ImageGetUtils";
    private static ImageGetUtils instance;
    private static String url = "https://cn.bing.com/cnhp/coverstory?d=";

    private static LruCache<String, Bitmap> mLruCache;

    public static ImageGetUtils getInstance() {
        if (instance == null) {
            synchronized (ImageGetUtils.class) {
                if (instance == null) {
                    instance = new ImageGetUtils();
                }
            }
        }
        return instance;
    }

    public ImageGetUtils() {
        Log.d(TAG, "ImageGetUtils CPU核心可用数: " + Runtime.getRuntime().availableProcessors());
        int cacheMemory = (int) (Runtime.getRuntime().maxMemory() / 4);
        mLruCache = new LruCache(cacheMemory);
    }


    public void loadImage(String data, ImageView imageView) {
        imageView.setTag(data);
        final WeakReference<ImageView> imgv = new WeakReference<>(imageView);
        if (imageView.getMeasuredWidth() == 0) {
            imageView.post(new Runnable() {
                @Override
                public void run() {

                }
            });
        } else {

        }
    }

    public void loadImage(final int resId, ImageView imageView) {
        imageView.setTag(resId);
        final WeakReference<ImageView> imgv = new WeakReference<>(imageView);

        if (mLruCache.get(String.valueOf(resId)) != null) {
            imageView.setImageBitmap(mLruCache.get(String.valueOf(resId)));
        } else {
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    Bitmap bitmap = ImageUtils.compressImage(resId, imgv.get());
                    imgv.get().setImageBitmap(bitmap);
                    mLruCache.put(String.valueOf(resId), bitmap);
                }
            };

            if (imageView.getMeasuredWidth() == 0) {
                imageView.post(runnable);
            } else {
                runnable.run();
            }

          //  new DownloadAsyncTask(imageView,String.valueOf(resId)).execute();
        }


    }

    class DownloadAsyncTask extends AsyncTask {
        private WeakReference<ImageView> weakReference;
        private String mDate;

        public DownloadAsyncTask(ImageView imageView,String date) {
            weakReference = new WeakReference<ImageView>(imageView);
            mDate=date;
        }

        @Override
        protected Object doInBackground(Object[] objects) {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url("http://hpimges.blob.core.chinacloudapi.cn/coverstory/watermark_jeanlafitte_zh-cn11969195990_1920x1080.jpg")
                    .get()
                    .build();
            Call call = client.newCall(request);
            try {
                Response response = call.execute();
                return ImageUtils.compressImage(response.body().byteStream(), weakReference.get());
            } catch (IOException e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);
            weakReference.get().setImageBitmap((Bitmap) o);
            Log.d(TAG, "onPostExecute: "+mDate);
//            mLruCache.put(String.valueOf(mDate), (Bitmap) o);
        }
    }

    private void downloadFile(final String url, final WeakReference<ImageView> imgv, final HttpCallBack httpCallBack) {
        Log.d(TAG, "downloadFile: " + url);
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "onResponse: 图片获取出错" + e.getMessage());
                httpCallBack.onError(-1, e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG, "onResponse: response" + response.body().contentLength());
                //  FilleUtils.saveFile(System.currentTimeMillis()+".jpg",response.body().byteStream());
                Log.d(TAG, "onResponse: 图片保存完成");
                ImageView imageView = imgv.get();
                if (imageView != null) {
                    httpCallBack.onSuccess(ImageUtils.compressImage(response.body().byteStream(), imageView));
                }

            }
        });
    }


    public static interface HttpCallBack<T> {
        void onSuccess(T result);

        void onError(int code, String reasion);
    }
}
